package com.jiang.starter.redis.channel;

import lombok.SneakyThrows;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.lang.NonNull;

import java.util.Map;

/**
 * 执行包扫描逻辑
 */
public class ChannelRegistrar implements ImportBeanDefinitionRegistrar {

    @SneakyThrows
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, @NonNull BeanDefinitionRegistry registry) {

        // 获取扫描路径
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(ComponentScan.class.getName());
        String[] basePackages;
        if(annotationAttributes == null){
            String mainClassName = System.getProperty("sun.java.command");
            Class<?> mainClass = Class.forName(mainClassName);
            basePackages = new String[] {mainClass.getPackage().getName()};
        } else {
            basePackages = (String[]) annotationAttributes.get("value");
        }

        // 创建包扫描器并开始扫描
        ClassPathChannelScanner classPathMessageQueueScanner = new ClassPathChannelScanner(registry);
        classPathMessageQueueScanner.addIncludeFilter(new AnnotationTypeFilter(Topic.class));
        classPathMessageQueueScanner.scan(basePackages);
    }
}
